package org.example.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AIService {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private ResumeService resumeService;

    @Value("${ai.api.url}")
    private String aiApiUrl;

    @Value("${ai.api.key}")
    private String apiKey;

    private final RestTemplate restTemplate;

    public AIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public JsonNode analyzeResumeText(String resumeText, int userId) {
        try {
            //String prompt = createPrompt(resumeText);
            //String aiResponse = callAIApi(prompt);
            String aiResponse = callAIApi(resumeText);
            String content = getContent(aiResponse);
            //将ai的回答存进数据库
            resumeService.insertResume(userId,content);
            //格式化ai的回答
            return extractJsonFromResponse(aiResponse);
        } catch (Exception e) {
            throw new AIServiceException("简历分析失败: " + e.getMessage(), e);
        }
    }

//    /**
//     * 分析简历内容
//     * @param resumeText
//     * @param userId
//     * @return
//     */
//    public String analyzeResumeText(String resumeText, int userId) {
//        try {
//            String aiResponse = callAIApi(resumeText);
//            String content = getContent(aiResponse);
//            //将ai的回答存进数据库
//            resumeService.insertResume(userId,content);
//            //格式化ai的回答
//            return content;
//        } catch (Exception e) {
//            throw new AIServiceException("简历分析失败: " + e.getMessage(), e);
//        }
//    }

    public String callAIApi(String prompt) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", prompt);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", Collections.singletonList(message));
            requestBody.put("max_tokens", 4000);
            //requestBody.put("response_format", Map.of("type", "json_object"));
            requestBody.put("temperature", 0.2);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            //调用AI接口
            ResponseEntity<String> response = restTemplate.exchange(
                    aiApiUrl, HttpMethod.POST, entity, String.class);

            if (response.getStatusCode() != HttpStatus.OK) {
                throw new AIServiceException("AI API请求失败: HTTP状态码 " + response.getStatusCode());
            }
            log.info("ai的回答{}",response.getBody());
            return response.getBody();
        } catch (RestClientException e) {
            throw new AIServiceException("调用AI API时发生网络错误: " + e.getMessage(), e);
        }
    }

    private JsonNode extractJsonFromResponse(String response) {
        try {
            JsonNode root = objectMapper.readTree(response);
            JsonNode choices = root.path("choices");

            if (!choices.isArray() || choices.isEmpty()) {
                throw new AIServiceException("无效的AI响应格式: 缺少choices数组");
            }

            JsonNode message = choices.get(0).path("message");
            if (message.isMissingNode()) {
                throw new AIServiceException("无效的AI响应格式: 缺少message对象");
            }

            String content = message.path("content").asText();
            if (content == null || content.trim().isEmpty()) {
                throw new AIServiceException("AI响应内容为空");
            }

            // 查找JSON对象的起始和结束位置
            int jsonStart = content.indexOf('{');
            int jsonEnd = content.lastIndexOf('}') + 1;

            if (jsonStart == -1 || jsonEnd == -1 || jsonEnd <= jsonStart) {
                throw new AIServiceException("AI返回的内容不包含有效JSON");
            }

            String jsonContent = content.substring(jsonStart, jsonEnd);
            return objectMapper.readTree(jsonContent);
        } catch (Exception e) {
            throw new AIServiceException("解析AI响应失败: " + e.getMessage(), e);
        }
    }

    public String getContent(String jsonStr) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(jsonStr);

        String content = rootNode.path("choices")
            .get(0)
            .path("message")
            .path("content")
            .asText();
        System.out.println("content的内容"+content);
        return content;
    }

    // 自定义异常类
    public static class AIServiceException extends RuntimeException {
        public AIServiceException(String message) {
            super(message);
        }

        public AIServiceException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}
